package com.bookcity.front.webfront.ctrl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bookcity.front.webfront.vo.Login;
import com.bookcity.front.webfront.vo.LoginResult;
import com.bookcity.front.webfront.vo.TokenResult;
import com.ruoyi.common.utils.http.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

/**
 * @author oldliu
 * @since 1.0
 */
public class Douyin {
    //private static final String LOGIN="https://developer.toutiao.com/api/apps/v2/jscode2session";
    private static final String LOGIN="https://open-sandbox.douyin.com/api/apps/v2/jscode2session";

    private static final Logger log = LoggerFactory.getLogger(Douyin.class);

    /**
     * json格式发送对象
     * @param lobin
     * @return
     */
    public static TokenResult getToken(Login lobin){
        String s = sendPostJSON("https://developer.toutiao.com/api/apps/v2/token", JSON.toJSONString(lobin));
        return (TokenResult) JSON.parse(s);
    }
    public static TokenResult getToken(String appid, String secrit, String code){
        Login l=new Login();
        l.setAppid(appid);
        l.setSecret(secrit);
        l.setCode(code);
        String s = sendPostJSON("https://developer.toutiao.com/api/apps/v2/token", JSON.toJSONString(l));
        return (TokenResult)JSON.parse(s);
    }
    public static LoginResult login(Login lobin){
        System.out.println("login:"+lobin);
        String s = sendPostJSON(LOGIN, JSON.toJSONString(lobin));
        return (LoginResult) JSON.parseObject(s,LoginResult.class);
    }

    public static void main(String[] args) {
        String code="b0SbXuZyKYiPvnCWUnmmdN8tUHyp5qi7tFWRmXpORTGoRgzN1PvZA1a6JpKvRR3OXLVLZ8D2Jcw8ScsLJ8dOttwtzYAuNVmT5DR_jPjbiq4nH6etltOGUYzHl1U";
        Login l=new Login("ttdb04adb944386a1b01","c48c2a88003426b36710f6e00fe8c79b743059ff",code);
        System.out.println(login(l));
    }

    public static String sendPostJSON(String url, String param)
    {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try
        {
            log.info("sendPost - {}", url);
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            //conn.setRequestProperty("connection", "Keep-Alive");
            //conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("Content-type","application/json");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null)
            {
                result.append(line);
            }
            log.info("recv - {}", result);
        }
        catch (ConnectException e)
        {
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
        }
        finally
        {
            try
            {
                if (out != null)
                {
                    out.close();
                }
                if (in != null)
                {
                    in.close();
                }
            }
            catch (IOException ex)
            {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }
}
